{% extends "base.html" %}

{% block title %}会议室详情{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h2 id="roomName">会议室详情</h2>
            <div>
                <button id="backBtn" class="btn btn-secondary">返回列表</button>
                <button id="editBtn" class="btn btn-warning" style="display: none;">编辑</button>
                <button id="deleteBtn" class="btn btn-danger" style="display: none;">删除</button>
            </div>
        </div>
        <div class="card-body">
            <div id="roomDetails">
                <p><strong>ID：</strong><span id="roomId"></span></p>
                <p><strong>名称：</strong><span id="roomNameDetail"></span></p>
                <p><strong>容量：</strong><span id="roomCapacity"></span>人</p>
                <p><strong>位置：</strong><span id="roomLocation"></span></p>
                <p><strong>设施：</strong><span id="roomFacilities"></span></p>
                <p><strong>状态：</strong><span id="roomStatus"></span></p>
                <p><strong>创建时间：</strong><span id="roomCreatedAt"></span></p>
            </div>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <h3>会议室排期</h3>
        </div>
        <div class="card-body">
            <div id="roomScheduleTableContainer">
                <!-- 会议室排期表格将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <button id="reserveBtn" class="btn btn-primary btn-lg mt-4">预约此会议室</button>
</div>

<!-- Hidden input for admin status -->
<input type="hidden" id="isAdmin" value="{{ is_admin }}">
<input type="hidden" id="roomIdInput" value="{{ room_id }}">

<script>
    const isAdmin = document.getElementById('isAdmin').value === 'True';
    const roomId = document.getElementById('roomIdInput').value;
    
    // 根据用户权限显示/隐藏管理按钮
    if (isAdmin) {
        document.getElementById('editBtn').style.display = 'inline-block';
        document.getElementById('deleteBtn').style.display = 'inline-block';
    }

    // 加载会议室详情
    async function loadRoomDetails() {
        try {
            const response = await axios.get(`/api/rooms/${roomId}`);
            const room = response.data;
            
            // 更新页面标题
            document.getElementById('roomName').textContent = room.name;
            document.title = `${room.name} - 会议室详情`;
            
            // 更新详情
            document.getElementById('roomId').textContent = room.id;
            document.getElementById('roomNameDetail').textContent = room.name;
            document.getElementById('roomCapacity').textContent = room.capacity;
            document.getElementById('roomLocation').textContent = room.location;
            document.getElementById('roomFacilities').textContent = room.facilities || '无';
            document.getElementById('roomStatus').textContent = room.is_active ? '可用' : '不可用';
            document.getElementById('roomCreatedAt').textContent = new Date(room.created_at).toLocaleString();
        } catch (error) {
            console.error('Error loading room details:', error);
            alert('加载会议室详情失败');
        }
    }

    // 加载会议室排期
    async function loadRoomSchedule() {
        try {
            const response = await axios.get(`/api/meetings/room/${roomId}`);
            const meetings = response.data;
            renderSchedule(meetings);
        } catch (error) {
            console.error('Error loading room schedule:', error);
            document.getElementById('roomScheduleTableContainer').innerHTML = '<p class="text-center">加载会议室排期失败</p>';
        }
    }

    // 渲染会议室排期为表格
    function renderSchedule(meetings) {
        const container = document.getElementById('roomScheduleTableContainer');
        if (!meetings || meetings.length === 0) {
            container.innerHTML = '<p class="text-center">暂无排期</p>';
            return;
        }
        let html = `<table class="table table-striped">
            <thead>
                <tr>
                    <th>标题</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>创建者</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>`;
        meetings.forEach(meeting => {
            const startTime = new Date(meeting.start_time).toLocaleString();
            const endTime = new Date(meeting.end_time).toLocaleString();
            const ownerName = meeting.owner_name || (meeting.owner ? meeting.owner.username : '未知');
            let statusText = '';
            if (meeting.is_cancelled) {
                statusText = '<span class="badge bg-danger">已取消</span>';
            } else {
                const now = new Date();
                const sTime = new Date(meeting.start_time);
                const eTime = new Date(meeting.end_time);
                if (now < sTime) {
                    statusText = '<span class="badge bg-primary">待开始</span>';
                } else if (now > eTime) {
                    statusText = '<span class="badge bg-secondary">已结束</span>';
                } else {
                    statusText = '<span class="badge bg-success">进行中</span>';
                }
            }
            html += `<tr>
                <td>${meeting.title}</td>
                <td>${startTime}</td>
                <td>${endTime}</td>
                <td>${ownerName}</td>
                <td>${statusText}</td>
            </tr>`;
        });
        html += '</tbody></table>';
        container.innerHTML = html;
    }

    // 删除会议室
    async function deleteRoom() {
        if (confirm('确定要删除这个会议室吗？')) {
            try {
                const response = await axios.delete(`/api/rooms/${roomId}`);
                if (response.status === 204) {
                    alert('删除成功');
                    window.location.href = '/rooms';
                } else {
                    alert('删除会议室失败');
                }
            } catch (error) {
                console.error('Error deleting room:', error);
                alert('删除会议室失败');
            }
        }
    }

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 设置token
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        }
        
        // 加载数据
        loadRoomDetails();
        loadRoomSchedule();
        
        // 绑定事件
        document.getElementById('backBtn').addEventListener('click', () => {
            window.location.href = '/rooms';
        });
        
        document.getElementById('editBtn').addEventListener('click', () => {
            window.location.href = `/rooms/${roomId}/edit`;
        });
        
        document.getElementById('deleteBtn').addEventListener('click', deleteRoom);
        
        document.getElementById('reserveBtn').addEventListener('click', () => {
            window.location.href = `/meetings/create?room=${roomId}`;
        });
    });
</script>
{% endblock %} 